import { useParams } from 'react-router-dom';
import { useEffect, useState } from 'react';
import axios from 'axios';
import { LeftOutlined } from '@ant-design/icons';
import { Card, Typography, Row, Col, Button, Space, message } from 'antd';

const { Title, Text } = Typography;

const ArticleDetail = () => {
    const { article_id } = useParams(); // 获取 URL 中的 id 参数
    const [article, setArticle] = useState(null);
    const [translation, setTranslation] = useState(null);
    const [isFavorited, setIsFavorited] = useState(false); // 用于判断文章是否已被收藏

    useEffect(() => {
        if (!article_id) {
            console.error("没有找到 articleId");
            return;
        }

        // 获取文章内容
        axios.get(`/api/articles/get/${article_id}`)
            .then(response => setArticle(response.data))
            .catch(error => console.error('Error fetching article:', error));

        // 获取翻译内容
        axios.get(`/api/translations/getbyarticle/${article_id}`)
            .then(response => setTranslation(response.data))
            .catch(error => console.error('Error fetching translation:', error));

        // 检查该文章是否已收藏
        const user = JSON.parse(localStorage.getItem('userInfo'));
        if (user && user.userId) {
            axios.get(`/api/favorites/check`, { params: { userId: user.userId, articleId: article_id } })
                .then(response => setIsFavorited(response.data.isFavorited))
                .catch(error => console.error('Error checking favorite status:', error));
        }
    }, [article_id]);

    // 预处理文本：将对话部分处理成独立句子，避免丢失内容
    const preProcessText = (text) => {
        return text
            .replace(/<br\s*\/?>/gi, '【换行符】') // 替换换行符
            .replace(/\n/g, '【换行符】')         // 替换换行符
            .replace(/([。！？\n])/g, '$1\n')      // 句末加上换行符
            .replace(/"([^"]+)"/g, '【对话开始】$1【对话结束】'); // 将引号内的对话提取
    };

    // 后处理文本：恢复原始的换行符和对话格式
    const postProcessText = (text) => {
        return text
            .replace(/【换行符】/g, '\n')        // 恢复换行符
            .replace(/【对话开始】/g, '"')      // 恢复对话引号
            .replace(/【对话结束】/g, '"')      // 恢复对话引号
            .replace(/(\n)+/g, '\n');            // 确保换行符之间没有多余空行
    };

    // 如果数据尚未加载，显示加载中
    if (!article) {
        return <p>加载中...</p>;
    }

    // 收藏文章的点击事件（不需要 token）
    const handleFavorite = async (article_id) => {
        try {
            const user = JSON.parse(localStorage.getItem('userInfo'));
            if (!user || !user.userId) {
                message.info('请先登录');
                return;
            }

            const userId = user.userId;
            const articleId = parseInt(article_id, 10);

            const response = await axios.post('/api/favorites/add', null, {
                params: { userId, articleId }
            });

            if (response.status === 200) {
                setIsFavorited(true);
                message.success('文章已添加到收藏');
            } else {
                message.error('收藏失败，请重试');
            }
        } catch (error) {
            console.error('Error adding to favorites:', error);
            message.error('收藏失败，请重试');
        }
    };

    const handleRemoveFavorite = async (article_id) => {
        try {
            const user = JSON.parse(localStorage.getItem('userInfo'));
            if (!user || !user.userId) {
                message.info('请先登录');
                return;
            }

            const userId = user.userId;
            const articleId = parseInt(article_id, 10);

            const response = await axios.delete('/api/favorites/remove', {
                params: { userId, articleId }
            });

            if (response.status === 200) {
                setIsFavorited(false);
                message.success('文章已从收藏中移除');
            } else {
                message.error('取消收藏失败，请重试');
            }
        } catch (error) {
            console.error('Error removing from favorites:', error);
            message.error('取消收藏失败，请重试');
        }
    };

    const handleGoBack = (event) => {
        event.preventDefault(); // 阻止默认的链接行为
        window.history.back(); // 返回上一页
    };

    return (
        <div>
           <Button icon={<LeftOutlined />} type="primary" onClick={handleGoBack} style={{ width:100,display: 'flex', alignItems: 'center', color:'#23153C',background:'white',marginLeft:30,marginTop:30 }}>
                <span style={{ marginLeft: 3 }}>返回</span>
            </Button> 
            <Row gutter={24} style={{ padding: '20px',marginTop:50,marginBottom:100 }} justify="center">
            
            {/* 文章部分 */}
            <Col span={12}>
                <Card
                    title={<Title level={3} style={{ color: '#211f3f' }}>{article.title}</Title>}
                    bordered={false}
                    style={{
                        minHeight: '300px',
                        borderRadius: '12px',
                        boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)',
                        backgroundColor: '#f7f7fb',
                        padding: '20px'
                    }}
                >
                    <Text style={{
                        color: '#2c3e50',
                        fontSize: '16px',
                        whiteSpace: 'pre-wrap',  // 保留换行
                        textAlign: 'left',       // 保证文本从左边对齐
                        wordWrap: 'break-word',  // 确保长单词也会换行
                    }}>
                        {postProcessText(article ? preProcessText(article.original_text) : '')}
                    </Text>
                    <br />
                    <Space style={{ marginTop: '20px' }}>
                        {!isFavorited ? (
                            <Button
                                type="primary"
                                onClick={() => handleFavorite(article_id)}
                                style={{
                                    backgroundColor: '#211f3f',
                                    borderColor: '#2980b9',
                                    borderRadius: '8px',
                                    fontWeight: 'bold',
                                }}
                            >
                                收藏文章
                            </Button>
                        ) : (
                            <Button
                                type="danger"
                                onClick={() => handleRemoveFavorite(article_id)}
                                style={{
                                    backgroundColor: '#f7f7f7',
                                    borderColor: '#211f3f',
                                    borderRadius: '8px',
                                    fontWeight: 'bold',
                                }}
                            >
                                取消收藏
                            </Button>
                        )}
                    </Space>
                </Card>
            </Col>

            {/* 翻译部分 */}
            <Col span={12}>
                <Card
                    title={<Title level={3} style={{ color: '#211f3f' }}>{translation?.translatedTitle || '翻译内容'}</Title>}
                    bordered={false}
                    style={{
                        minHeight: '300px',
                        borderRadius: '12px',
                        boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)',
                        backgroundColor: '#f7f7fb',
                        padding: '20px'
                    }}
                >
                    <Text style={{
                        color: '#211f3f',
                        fontSize: '16px',
                        whiteSpace: 'pre-wrap',  // 保留换行
                        textAlign: 'left',       // 保证文本从左边对齐
                        wordWrap: 'break-word',  // 确保长单词也会换行
                    }}>                        
                        {postProcessText(translation?.translatedText || '无翻译')}
                    </Text>
                </Card>
            </Col>
        </Row>
        </div>
        
    );
};

export default ArticleDetail;